package com.runfast.waimai.web.controller.base;

import com.runfast.common.utils.SessionContext;
import com.runfast.common.web.entity.Result;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.*;
import com.runfast.waimai.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;
import java.util.*;

/**
 * ${DESCRIPTION}
 *
 * @author chenzheng
 * @create 2018-05-05 17:24
 **/
@RestController("roleController")
@RequestMapping("/server/role")
public class RoleController {

    @Autowired
    private BaseRoleService baseRoleService;
    @Autowired
    private BaseRolePurviewService baseRolePurviewService;
    @Autowired
    private BaseUserRoleService baseUserRoleService;
    @Autowired
    private WaiMaiRunfastAgentbusinessService waiMaiRunfastAgentbusinessService;
    @Autowired
    private BasePurviewService basePurviewService;
    /**
     * 角色列表
     */
    @GetMapping("/list")
    public Result list(@PageableDefault Pageable pageable,BaseRole role){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentaccounts=SessionContext.getCurrentRunfastAgentaccounts();
        BaseRoleExample example=new BaseRoleExample();
        BaseRoleExample.Criteria exampleCriteria=example.createCriteria();
        List<BaseRole> list=new ArrayList<BaseRole>();
        Map<Object,Object> map=new HashMap<Object, Object>();
        Integer total=0;
        /**代理商多选*/
        if(StringUtils.isNotBlank(role.getAgentIds())){
            List<String> result = Arrays.asList(StringUtils.split(role.getAgentIds(),","));
            if(result.size()>0){
                List<Integer> in=new ArrayList<Integer>();
                for(String s:result){
                    in.add(StringUtil.stringToInteger(s));
                }
                exampleCriteria.andAgentIdIn(in);
            }
        }
        if(role.getAgentId()!=null){
            exampleCriteria.andAgentIdEqualTo(role.getAgentId());
        }
        if(StringUtils.isNotBlank(role.getRname())){
            exampleCriteria.andRnameLike("%"+role.getRname()+"%");
        }
        //如果不是超级管理员，则只查询自己
        if( admin!=null && admin.getType()==1){
            //超级管理员
            if(role.getAgentId()==null){
                exampleCriteria.andAgentIdIsNull();
            }
            list=baseRoleService.selectByExampleWithBLOBsWithPageable(example,pageable);
            total=baseRoleService.countByExample(example);
            map.put("list",list);
            map.put("total",total);
        }else if(admin!=null && admin.getType()==2 && agentaccounts!=null){
            WaiMaiRunfastAgentbusiness  agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(agentaccounts.getAgentid());
            if(agentbusiness!=null){
                exampleCriteria.andAgentIdEqualTo(agentaccounts.getAgentid());
                list=baseRoleService.selectByExampleWithBLOBsWithPageable(example,pageable);
                total=baseRoleService.countByExample(example);
                map.put("list",list);
                map.put("total",total);
            }else{return Result.fail(null,"找不到对应的代理商！");}
        }else{return Result.fail(null,"未登录，重新登录！");}
        if(list.size()>0){
            for(BaseRole r:list){
                List<BaseUser> userList=baseUserRoleService.queryUserList(r.getRid());
                r.setBaseUsers(userList);

                List<Integer> purviewIdListlist=baseRolePurviewService.queryMenuIdList1(r.getRid());
                List<Integer> purviewIdListlist1=baseRolePurviewService.queryMenuIdList2(r.getRid());
                if(purviewIdListlist1.size()>0){
                     for(Integer integer:purviewIdListlist1){
                         BasePurviewExample example1=new BasePurviewExample();
                         example1.createCriteria().andByidEqualTo(integer);
                         Integer integer1=basePurviewService.countByExample(example1);
                         if(integer1==0){
                             purviewIdListlist.add(integer);
                         }
                     }
                }
                r.setPurviewIdList(purviewIdListlist);
            }
        }
        return Result.ok(null,map);
    }

    /*** 角色列表*/
    @GetMapping("/select")
    public Result select(Integer agentId){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        BaseRoleExample example=new BaseRoleExample();
        if(admin!=null &&  admin.getType()==2 && agentAccounts!=null){
            if(agentId!=null){
                 if(agentId.equals(agentAccounts.getAgentid())){
                     example.createCriteria().andAgentIdEqualTo(agentAccounts.getAgentid());
                 }else{return Result.fail(null,"只能查看自己的信息！");}
            }else{
                example.createCriteria().andAgentIdEqualTo(agentAccounts.getAgentid());
            }
        }else if(admin!=null && admin.getType()==1){
            //后台管理员
            if(agentId!=null){
                example.createCriteria().andAgentIdEqualTo(agentId);
            }else{
                example.createCriteria().andAgentIdIsNull();
            }
        }else{return Result.fail(null,"请重新登录！");}
        List<BaseRole> roleList = baseRoleService.selectByExampleWithBLOBs(example);
        return Result.ok(null,roleList);
    }

    /**
     * 角色信息
     */
    @GetMapping("/info")
    //@RequiresPermissions("server:role:info")
    public Result info(Integer rid){
        BaseRole role = baseRoleService.selectByPrimaryKey(rid);

        //查询角色对应的菜单
        List<Integer> menuIdList = baseRolePurviewService.queryPurviewIdList(rid);
        //role.setPurviewIdList(menuIdList);

        return Result.ok(null,role);
    }

    /**
     * 保存角色
     */
    @PostMapping("/save")
    public Result save(@RequestBody BaseRole role){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentaccounts=SessionContext.getCurrentRunfastAgentaccounts();
        if(role!=null && StringUtils.isNotBlank(role.getRname())){
            if(admin!=null && admin.getType()==2 && agentaccounts!=null){
                //代理商创建自己的角色
                if(role.getAgentId()!=null){
                    if(role.getAgentId().equals(agentaccounts.getAgentid())){
                        role.setAgentId(agentaccounts.getAgentid());
                    }else{return Result.fail(null,"不能创建不属于自己的部门！");}
                }else{
                    role.setAgentId(agentaccounts.getAgentid());
                }
                role.setCreateTime(new Date());
                baseRoleService.insert(role);
            }else if(admin!=null && admin.getType()==1){
                //后台
                if(role.getAgentId()!=null){
                   //后台创建代理商的角色
                    WaiMaiRunfastAgentbusiness  agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(role.getAgentId());
                    if(agentbusiness!=null){
                       role.setAgentId(agentbusiness.getId());
                    }else{return Result.fail(null,"找不到对应的代理商！");}
                }else{
                    //后台创建自己的角色
                }
                role.setCreateTime(new Date());
                baseRoleService.insert(role);
            }
        }else{return Result.fail(null,"传入参数不对！");}
        return Result.ok(null);
    }

    /**
     * 修改角色
     */
    @PostMapping("/update")
    public Result update(@RequestBody BaseRole role){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentaccounts=SessionContext.getCurrentRunfastAgentaccounts();
        if(role!=null && StringUtils.isNotBlank(role.getRname()) && role.getRid()!=null){
            BaseRole role1=baseRoleService.selectByPrimaryKey(role.getRid());
            if(role1!=null){
                if(admin!=null && admin.getType()==2 && agentaccounts!=null){
                    //代理商修改自己的角色
                    if(role.getAgentId()!=null){
                        if(role.getAgentId().equals(agentaccounts.getAgentid())){
                             role1.setAgentId(agentaccounts.getAgentid());
                        }else{return Result.fail(null,"不能修改不属于自己的部门！");}
                    }else{
                        role1.setAgentId(agentaccounts.getAgentid());
                    }
                    role1.setInfo(role.getInfo());
                    role1.setRname(role.getRname());
                    role1.setUpdateTime(new Date());
                    //BaseRoleExample example=new BaseRoleExample();
                    //example.createCriteria().andRidEqualTo(role1.getRid());
                    //baseRoleService.updateByExample(role1,example);
                    baseRoleService.updateByPrimaryKeySelective(role1);
                }else if(admin!=null && admin.getType()==1){
                    //后台
                    if(role.getAgentId()!=null){
                        //后台修改代理商的角色
                        WaiMaiRunfastAgentbusiness  agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(role.getAgentId());
                        if(agentbusiness!=null){
                            role1.setAgentId(agentbusiness.getId());
                        }else{return Result.fail(null,"找不到对应的代理商！");}
                    }else{
                        //后台创建自己的角色
                    }
                    role1.setInfo(role.getInfo());
                    role1.setRname(role.getRname());
                    role1.setUpdateTime(new Date());
                    BaseRoleExample example=new BaseRoleExample();
                    example.createCriteria().andRidEqualTo(role1.getRid());
                    //baseRoleService.updateByExample(role1,example);
                    baseRoleService.updateByPrimaryKeySelective(role1);
                }
            }else{return Result.fail(null,"找不到对应的部门！");}
        }else{return Result.fail(null,"传入参数不对！");}
        return Result.ok(null);
    }


    /*** 根据id给角色分配权限*/
     @GetMapping("/setPurviewsById")
     public Result setPurviewsById(Integer rid,String pIds){
         if(rid!=null){
             BaseRolePurviewExample example =new BaseRolePurviewExample();
             example.createCriteria().andRidEqualTo(rid);
             baseRolePurviewService.deleteByExample(example);
             if(StringUtils.isNotBlank(pIds)){
                 List<String> result = Arrays.asList(StringUtils.split(pIds,","));
                 for(String s:result){
                     BaseRolePurview b=new BaseRolePurview();
                     b.setRid(rid);
                     b.setPid(Integer.valueOf(s));
                     baseRolePurviewService.insert(b);
                 }
             }
         }else{return Result.fail(null,"传入参数不对！");}
         return  Result.ok(null);
     }
    /**
     * 根据角色id查询权限id的list
     */
    //@GetMapping("/selectByRid")
    public Result selectByRid(Integer rid){
        List<Integer> list=null;
        if(rid !=null){
            list=baseRolePurviewService.queryPurviewIdList(rid);
        }else{
            list=null;
        }
        return Result.ok(null,list);
    }

    /**
     * 删除角色---暂时不实现
     */
    @PostMapping("/delete")
    //@RequiresPermissions("sys:role:delete")
    public Result delete(Integer rid){
        //List<Integer> list=baseRolePurviewService.queryPurviewIdList(rid);
        List<Integer> list1=baseUserRoleService.queryUserIdList(rid);
        if(list1.size()>0){
            return Result.fail(null,"有关联的数据，无法删除！");
        }else{
            baseRoleService.deleteByPrimaryKey(rid);
        }
        return Result.ok(null);
    }

}
